<?php

declare(strict_types=1);
/**
 * 
 */
namespace WanZ\App\User\Consumer;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Di\Annotation\Inject;
use WanZ\App\User\Consumer\AbstractConsumer;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;

class Order extends AbstractConsumer
{
    private const PREFIX = 'orderEr:';

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    private $logger;

    /**
     * 获取用户优惠币相关信息
     * 
     * @return array
     * @throws CommonException
     */
    public function getDisCountCoinByUserId(): array
    {
        $result = $this->httpRequest()->get($this->getUrl('pay').'/discount/getUserGroupDiscountCoin', $this->data);

        if ($result['code'] != 1) {
            throw new CommonException(ErrorCode::THIRD_API_ERROR, self::PREFIX. $result['message']);
        }

        if (empty($result['data'])) {
            return [
                'isOpenDiscountCoin' => 0,
                'discountCoinBalance' => 0,
                'discountCoinNum' => 0
            ];
        }

        $wxBalance = $result['data']['wxBalance'] ?: 0;
        $aliBalance = $result['data']['aliBalance'] ?: 0;
        $disCountCoinBalance =$wxBalance + $aliBalance;
        if ($disCountCoinBalance > 0) {
            $disCountCoinBalance = $disCountCoinBalance / 100;
        }

        return [
            'isOpenDiscountCoin' => 1,
            'discountCoinBalance' => $disCountCoinBalance,
            'discountCoinNum' => $result['data']['discountCoinNum']
        ];
    }    

    /**
     * 初始化代理商的收益信息
     * 
     * @throws CommonException
     */
    public function initDealerProfitInfo()
    {
        $result = $this->httpRequest()->postJson($this->getUrl('pay').'/profit/add/dealerProfitInfo', $this->data);

        if ($result['code'] != 1) {
            throw new CommonException(ErrorCode::THIRD_API_ERROR, self::PREFIX. $result['message']);
        }
    }

    /**
     * 赠送用户广告费
     * 
    * @throws CommonException
     */
    public function givingUserAdvCost()
    {
        try {
            $result = $this->httpRequest()->postJson($this->getUrl('pay').'/transfer/user/request', $this->data);

            if ($result['code'] != 1) {
                throw new CommonException(ErrorCode::THIRD_API_ERROR, self::PREFIX. $result['message'] ?? '请求订单中心发起支付失败');
            }
        } catch (\Throwable $exception) {
            $this->logger->error('givingAdvCostError', [
                'errorMsg'     => $exception->getMessage(),
                'site'         => $exception->getFile().'|'.$exception->getLine(),
                'requestData'  => $this->data,
                'responseData' => $result ?? []
            ]);
        }
    }    
}
